package com.freestyle.seatabusiness.storage.config;

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.fasterxml.jackson.core.type.TypeReference;
import com.freestyle.common.JsonUtils;
import com.freestyle.sentinel.SentinelResourceAspectEx;
import com.freestyle.sentinel.config.SentinelConfig;
import lombok.Setter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * Sentinel限流配置
 * Created by rocklee on 2022/3/26 11:52
 */
@Configuration
@AutoConfigureBefore(SentinelConfig.class)
//@PropertySource(value = "classpath:/config/tsj-config.yml",factory = YamlPropertySourceFactory.class)
@ConfigurationProperties(prefix = "sentinel")
@Setter
public class SentinelFlowConfig implements InitializingBean {
  private String nacosAddrs;
  private String groupId;
  private String dataId;
  @Bean
  public SentinelResourceAspect sentinelResourceAspect() {
    return new SentinelResourceAspectEx(new SentinelGlobalHandler());
  }
  @PostConstruct
  public void init() throws Exception {
    //改为存放在nacos服务器 参阅 com.freestyle.seatabusiness.account.AccountApplicationTest.publishSentinelRule
      /*List<FlowRule> ruleList=new LinkedList<>();
      for(String res:new String[]{"getAccountList"}) {
        FlowRule rule = new FlowRule();
        rule.setCount(2);//限制每秒10 qps
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//以QPS限流
        rule.setResource(res);
        //rule.setControlBehavior()
        ruleList.add(rule);
      }
      FlowRuleManager.loadRules(ruleList);*/
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new NacosDataSource<>(nacosAddrs, groupId, dataId,
            source -> JsonUtils.fromJson(source, new TypeReference<List<FlowRule>>() {}));
    FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
  }
}
